<?php

namespace App\Store\Controllers\Member;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Store\Models\Member\Member;
use App\Common\Services\Store\Common as StoreCommon;
use App\Store\Models\Account\SiteStore;
use App\Store\Models\Member\MemberPointsChangelog;

use App\Common\Services\CommonExcelExport;
use App\Store\Models\Account\Account;
use App\Store\Models\Member\SiteMemberLv;
use Maatwebsite\Excel\Facades\Excel;
use App\Store\Services\Excel\DownloadTemp;
use App\Store\Services\Member\CommonMember;
use Illuminate\Support\Facades\DB;
use PhpOffice\PhpSpreadsheet\Shared\Date;

use App\Store\Validate\Member\Member as ValidateMemberMember;

/**
 * 会员信息
 */
class MemberController extends Controller
{
    /**
     * 获取列表
     */
    public function getlist(Request $request)
    {
        $list = Member::getList($request);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    /**
     * 获取详情
     */
    public function getinfo(Request $request)
    {
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = Member::with(['lvinfo', 'shoppingaccountinfo', 'storeinfo', 'sharememinfo'])->where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['info' => $info]]);
    }

    /**
     * 解绑会员
     */
    public function bandoutwxaccount(Request $request)
    {
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = Member::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        Member::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])
            ->update(['is_band_wxaccount' => 1, 'wx_app_open_id' => '', 'update_at' => time()]);


        return response()->json(['code' => '000', 'msg' => '解绑成功']);
    }


    /**
     * 通过手机号、会员卡号
     */
    public function getinfowithother(Request $request)
    {
        $mobile = $request->mobile ?? '';
        $mem_card_no = $request->mem_card_no ?? '';
        $real_name = $request->real_name ?? '';
        if ($mobile == '' && $mem_card_no == '' && $real_name == '') {

            return response()->json(['code' => '001', 'msg' => '无效搜索条件']);
        }
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $infolist = Member::where(['cp_id' => $cp_id, 'is_del' => 1])
            ->where('mobile', 'like', '%' . $mobile . '%')
            // ->where('mobile', 'like', $mobile . '%')
            ->where('mem_card_no', 'like', '%' . $mem_card_no . '%')
            ->where('real_name', 'like', '%' . $real_name . '%')
            ->get()->toArray();


        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['list' => $infolist]]);
    }

    /**
     * 补录会员
     */
    public function dopostadd(Request $request)
    {
        $req_data = $request->only([
            'store_id', 'real_name', 'mobile', 'mem_card_no', 'pre_money', 'points_total', 'points_used', 'points_current', 'share_mem_id',
            // 'share_mem_send_points',
            'member_lv', 'gender',
            // 'shopping_times',
            'lunar_bdate', 'solar_bdate', 'shopping_account_id', 'address',
            // 'last_shopping_at',
            'marry_date', 'remark'
        ]);


        $Validate = new ValidateMemberMember();
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);

        $store_ids = $accountinfo['store_ids'];
        $store_id = 0;
        if ($store_ids && is_numeric($store_ids) && intval($store_ids) > 0) {
            $store_id = intval($store_ids);
        }
        if ($store_id <= 0) {
            $store_id = isset($req_data['store_id']) ? intval($req_data['store_id']) : 0;
            if ($store_id <= 0) {
                return response()->json(['code' => '001', 'msg' => '请选择会员所属门店']);
            } else {
                $storeinfo = SiteStore::where(['id' => $store_id, 'cp_id' => $accountinfo['cp_id']])->first();
                if (!$storeinfo) {
                    return response()->json(['code' => '001', 'msg' => '无效门店参数']);
                }
            }
        }

        $isexist = Member::where([['cp_id', $accountinfo['cp_id']], ['mobile', $req_data['mobile']], ['is_del', 1]])->first();
        if ($isexist) {
            return response()->json(['code' => '001', 'msg' => '会员手机号已注册不允许重复']);
        }
        if (isset($req_data['mem_card_no']) && $req_data['mem_card_no'] != '') {
            $accountinfo = StoreCommon::getCurrentAccountinfo($request);
            $isexist = Member::where([['cp_id', $accountinfo['cp_id']], ['mem_card_no', $req_data['mem_card_no'], ['is_del', 1]]])->first();
            if ($isexist) {
                return response()->json(['code' => '001', 'msg' => '会员卡号已注册不允许重复']);
            }
        }


        $data = $req_data;
        $data['points_current'] = isset($req_data['points_current']) ? intval($req_data['points_current']) : 0;
        // $data['shopping_times']=isset($req_data['shopping_times'])?intval($req_data['shopping_times']):0;

        $data['create_account_id'] = $accountinfo['id'];
        $data['update_account_id'] = $accountinfo['id'];
        $data['create_account_real_name'] = $accountinfo['real_name'];
        $data['update_account_real_name'] = $accountinfo['real_name'];

        // $data['pre_money'] = intval($data['pre_money']);
        $data['points_total'] = intval($data['points_current']);
        // $data['points_used'] = intval($data['points_used']);
        $data['share_mem_id'] = isset($req_data['share_mem_id']) ? intval($req_data['share_mem_id']) : 0;
        // $data['share_mem_send_points'] = isset($req_data['share_mem_send_points'])?intval($req_data['share_mem_send_points']):0;
        $data['lunar_bdate'] = isset($req_data['lunar_bdate']) ? strval($data['lunar_bdate']) : '';
        $data['solar_bdate'] = isset($req_data['solar_bdate']) ? strval($data['solar_bdate']) : '';
        $data['shopping_account_id'] = isset($req_data['shopping_account_id']) ? intval($req_data['shopping_account_id']) : 0;
        $data['address'] = isset($req_data['address']) ? strval($data['address']) : '';
        // $data['last_shopping_at'] = isset($data['last_shopping_at']) ? strtotime($data['last_shopping_at']) : 0;
        $data['marry_date'] = isset($req_data['marry_date']) ? strtotime($data['marry_date']) : 0;
        $data['remark'] = isset($req_data['remark']) ? strval($data['remark']) : '';
        $data['cp_id'] = $accountinfo['cp_id'];
        $data['store_id'] = $store_id;
        $data['create_at'] = time();
        $data['update_at'] = time();
        $data['gender'] = (isset($data['gender']) && $data['gender'] > 0) ? $data['gender'] : 1;

        $level = SiteMemberLv::where([
            ['is_del', '=', 1],
            ['init_points_num', '<=', $data['points_current']]
        ])->orderBy('init_points_num', 'desc')
            ->first();
        if ($level) {
            $data['member_lv'] = $level->id;
        } else {
            $data['member_lv'] = 0;
        }


        $ins_mem_id = Member::create($data)->id;
        CommonMember::setMemInitPoints($request, $ins_mem_id);
        return response()->json(['code' => '000', 'msg' => '新增成功']);
    }

    /**
     * 编辑会员
     */
    public function dopostedit(Request $request)
    {
        $req_data = $request->only([
            'id', 'store_id', 'real_name', 'mobile', 'mem_card_no', 'pre_money', 'points_total', 'points_used', 'points_current', 'share_mem_id',
            // 'share_mem_send_points',
            'member_lv', 'gender',
            // 'shopping_times',
            'lunar_bdate', 'solar_bdate', 'shopping_account_id', 'address',
            // 'last_shopping_at',
            'marry_date', 'remark'
        ]);
        $Validate = new ValidateMemberMember();
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);

        $info = Member::where(['id' => $req_data['id'], 'cp_id' => $accountinfo['cp_id'], 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        $isexist = Member::where([['id', '<>', $req_data['id']], ['cp_id', $accountinfo['cp_id']], ['mobile', $req_data['mobile']], ['is_del', 1]])->first();
        if ($isexist) {
            return response()->json(['code' => '001', 'msg' => '会员手机号已注册不允许重复']);
        }
        if ($req_data['mem_card_no']) {
            $accountinfo = StoreCommon::getCurrentAccountinfo($request);
            $isexist = Member::where([['id', '<>', $req_data['id']], ['cp_id', $accountinfo['cp_id']], ['mem_card_no', $req_data['mem_card_no']], ['is_del', 1]])->first();
            if ($isexist) {
                return response()->json(['code' => '001', 'msg' => '会员卡号已注册不允许重复']);
            }
        }
        $store_id = $request->store_id;
        if ($store_id <= 0) {
            $store_id = isset($req_data['store_id']) ? intval($req_data['store_id']) : 0;
            if ($store_id <= 0) {
                return response()->json(['code' => '001', 'msg' => '请选择会员所属门店']);
            } else {
                $storeinfo = SiteStore::where(['id' => $store_id, 'cp_id' => $accountinfo['cp_id']])->first();
                if (!$storeinfo) {
                    return response()->json(['code' => '001', 'msg' => '无效门店参数']);
                }
            }
        }

        if (isset($req_data['share_mem_id']) && intval($req_data['share_mem_id']) > 0 && $req_data['share_mem_id'] == $info->id) {
            return response()->json(['code' => '001', 'msg' => '推荐人不允许为自己']);
        }


        $data = $req_data;
        $data['store_id'] = $store_id;
        $data['points_current'] = isset($req_data['points_current']) ? intval($req_data['points_current']) : 0;
        // $data['shopping_times']=isset($req_data['shopping_times'])?intval($req_data['shopping_times']):0;
        $data['update_account_id'] = $accountinfo['id'];
        $data['update_account_real_name'] = $accountinfo['real_name'];
        // $data['pre_money'] = intval($data['pre_money']);
        // $data['points_total'] = intval($data['points_total']);
        // $data['points_used'] = intval($data['points_used']);
        $data['points_current'] = intval($data['points_current']);
        $data['share_mem_id'] = isset($req_data['share_mem_id']) ? intval($req_data['share_mem_id']) : 0;
        // $data['share_mem_send_points'] = isset($req_data['share_mem_send_points'])?intval($req_data['share_mem_send_points']):0;
        $data['member_lv'] = intval($data['member_lv']);
        $data['lunar_bdate'] = isset($req_data['lunar_bdate']) ? strval($data['lunar_bdate']) : '';
        $data['solar_bdate'] = isset($req_data['solar_bdate']) ? strval($data['solar_bdate']) : '';
        $data['shopping_account_id'] = isset($req_data['shopping_account_id']) ? intval($req_data['shopping_account_id']) : 0;
        $data['address'] = isset($req_data['address']) ? strval($data['address']) : '';
        // $data['last_shopping_at'] = $data['last_shopping_at'] ? strtotime($data['last_shopping_at']) : 0;
        $data['marry_date'] = isset($req_data['marry_date']) ? strtotime($data['marry_date']) : 0;
        $data['remark'] = isset($req_data['remark']) ? strval($data['remark']) : '';
        $data['update_at'] = time();
        $data['gender'] = (isset($data['gender']) && $data['gender'] > 0) ? $data['gender'] : 1;


        if ($info->points_current > $data['points_current']) {
            return response()->json(['code' => '001', 'msg' => '编辑当前积分不能小于用户当前积分']);
        }

        $data['points_total'] = $info->points_current + ($data['points_current'] - $info->points_current);
        Member::where(['id' => $info['id']])->update($data);
        CommonMember::checkMemLv($info->id);//会员升级


        return response()->json(['code' => '000', 'msg' => '会员编辑成功']);
    }

    /**
     * 一键转出
     */
    public function storememchangestore(Request $request)
    {

        $old_store_id = intval($request->old_store_id);
        $target_store_id = intval($request->target_store_id);
        if ($old_store_id <= 0 || $target_store_id <= 0 || $old_store_id == $target_store_id) {

            return response()->json(['code' => '001', 'msg' => '无效门店参数']);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $old_store_info = SiteStore::where(['id' => $old_store_id, 'cp_id' => $cp_id])->first();
        if (!$old_store_info) {
            return response()->json(['code' => '001', 'msg' => '无效所属门店参数']);
        }
        $target_store_info = SiteStore::where(['id' => $target_store_id, 'cp_id' => $cp_id])->first();

        if (!$target_store_info) {
            return response()->json(['code' => '001', 'msg' => '无效目标门店参数']);
        }
        Member::where(['cp_id' => $cp_id, 'store_id' => $old_store_id])->update(['store_id' => $target_store_id]);

        return response()->json(['code' => '000', 'msg' => '一键转出操作成功']);
    }

    /**
     * 批量清空积分
     */
    public function domoreresetpoints(Request $request)
    {
        $ids = $request->ids ?? '';
        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        if (count($ids) <= 0) {
            return response()->json(['code' => '001', 'msg' => '无效会员参数']);
        }
        $memlist = Member::where(['cp_id' => $cp_id, 'is_del' => 1])->whereIn('id', $ids)->get()->toArray();

        if (count($memlist) != count($ids)) {
            return response()->json(['code' => '001', 'msg' => '无效会员参数']);
        }
        $ins_data = [];
        foreach ($memlist as $info) {
            $valdata = [
                'cp_id' => $cp_id,
                'mem_id' => $info['id'],
                'type' => 21,
                'store_id' => $info['store_id'],
                'change_val' => $info['points_current'],
                'change_before' => $info['points_current'],
                'change_after' => 0,
                'sales_account_id' => $accountinfo['id'],
                'loginfo' => json_encode(['title' => '积分清零']),
                'create_account_id' => $accountinfo['id'],
                'update_account_id' => $accountinfo['id'],
                'create_account_real_name' => $accountinfo['real_name'],
                'update_account_real_name' => $accountinfo['real_name'],
                'create_at' => time(),
                'update_at' => time(),
                'remark' => '',
            ];
            $ins_data[] = $valdata;
        }

        DB::beginTransaction();
        try {
            MemberPointsChangelog::insert($ins_data);
            Member::where(['cp_id' => $cp_id, 'is_del' => 1])->whereIn('id', $ids)->update(['points_current' => 0, 'update_at' => time()]);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '批量清空积分操作失败' . $e->getMessage()]);
        }

        return response()->json(['code' => '000', 'msg' => '批量清空积分操作成功']);
    }

    /**
     * 批量删除
     */
    public function domoredel(Request $request)
    {
        $ids = $request->ids ?? '';
        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        if (count($ids) <= 0) {
            return response()->json(['code' => '001', 'msg' => '无效会员参数']);
        }
        $count = Member::where(['cp_id' => $cp_id, 'is_del' => 1])->whereIn('id', $ids)->count();

        if ($count != count($ids)) {
            return response()->json(['code' => '001', 'msg' => '无效会员参数']);
        }
        Member::where(['cp_id' => $cp_id, 'is_del' => 1])->whereIn('id', $ids)->update(['is_del' => 2, 'del_at' => time()]);
        return response()->json(['code' => '000', 'msg' => '批量删除成功']);
    }

    /**
     * 导出
     */
    public function doexport(Request $request)
    { //isgetall=1;
        $list = Member::getList($request)['list'];
        $exceldata = [];
        $row = [
            ['start_store' => '会员列表'],
            [
                'store_name' => '所属门店',
                'is_band_wxaccount' => '是否绑定微信',
                'real_name' => '姓名',
                'gender' => '性别',
                'mobile' => '手机号码',
                'mem_card_no' => '会员卡号',
                'pre_money' => '预存金额',
                'points_total' => '总得积分',
                'points_used' => '使用积分',
                'points_current' => '当前积分',
                'share_mem_id' => '推荐人',
                'share_mem_send_points' => '推荐人所得积分',
                'shopping_times' => '消费次数',
                'member_lv' => '会员等级',
                'lunar_bdate' => '农历生日',
                'solar_bdate' => '公历生日',
                'shopping_account_id' => '导购',
                'address' => '地址',
                'last_shopping_at' => '最近购买时间',
                'create_at' => '注册时间',
                'marry_date' => '结婚纪念日',
                'remark' => '备注',
                'update_account_real_name' => '更新人',
                'update_at' => '更新时间',
            ]
        ];
        foreach ($list as $val) {
            $exceldata[] = [
                'store_name' => $val['storeinfo']['store_name'],
                'is_band_wxaccount' => $val['is_band_wxaccount'] == 1 ? '否' : '是',
                'real_name' => $val['real_name'],
                'gender' => $val['gender'] == 1 ? '男' : ($val['gender'] == 2 ? '女' : ''),
                'mobile' => $val['mobile'],
                'mem_card_no' => $val['mem_card_no'],
                'pre_money' => $val['pre_money'] / 100,
                'points_total' => $val['points_total'],
                'points_used' => $val['points_used'],
                'points_current' => $val['points_current'],
                'share_mem_id' => Member::where(['id' => $val['share_mem_id']])->value('real_name'),
                'share_mem_send_points' => $val['share_mem_send_points'],
                'shopping_times' => $val['shopping_times'],
                'member_lv' => $val['lvinfo'] ? $val['lvinfo']['lv_name'] : '',
                'lunar_bdate' => $val['lunar_bdate'],
                'solar_bdate' => $val['solar_bdate'],
                'shopping_account_id' => $val['shoppingaccountinfo'] ? $val['shoppingaccountinfo']['real_name'] : '',
                'address' => $val['address'],
                'last_shopping_at' => $val['last_shopping_at'] > 0 ? date('Y-m-d H:i:s', $val['last_shopping_at']) : '',
                'create_at' => $val['create_at'] > 0 ? date('Y-m-d H:i:s', $val['create_at']) : '',
                'marry_date' => $val['marry_date'] > 0 ? date('Y-m-d', $val['marry_date']) : '',
                'remark' => $val['remark'],
                'update_account_real_name' => $val['update_account_real_name'],
                'update_at' => $val['update_at'] > 0 ? date('Y-m-d H:i:s', $val['update_at']) : '',
            ];
        }

        $filename = '会员信息导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);
    }

    /**
     * 下载模板
     */
    public function dodownload(Request $request)
    {
        $row = [['手机号码', '卡号', '姓名', '性别', '会员等级', '生日', '当前积分', '业务员', '地址', '备注']];
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $options = [
            'D' => ['男', '女'],
            'E' => SiteMemberLv::where(['cp_id' => $cp_id, 'is_del' => 1])->pluck('lv_name')->toArray(),
        ];
        $dataTypes = [
            'J' => 'string' // Set column J (备注) as string type
        ];
        $datawith = [
            'A' => '25',
            'B' => '25',
            'C' => '25',
            'D' => '25',
            'E' => '25',
            'F' => '25',
            'G' => '25',
            'H' => '25',
            'I' => '25',
            'J' => '40',
        ];
        $filename = '会员信息导入模板_' . time() . '.xlsx';
        return Excel::download(new DownloadTemp($row, $options, $datawith,[],$dataTypes), $filename);
    }

    /**
     * 导入
     */
    /**
     * 导入
     */
    public function doimport(Request $request)
    {
        set_time_limit(-1);
        $filepathname = $request->filepathname;

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $store_ids = $accountinfo['store_ids'];
        $store_id = 0;
        if ($store_ids && is_numeric($store_ids) && intval($store_ids) > 0) {
            $store_id = intval($store_ids);
        }
        if ($store_id <= 0) {
            $store_id = isset($request->store_id) ? intval($request->store_id) : 0;
            if ($store_id <= 0) {
                return response()->json(['code' => '001', 'msg' => '请选择会员所属门店']);
            } else {
                $storeinfo = SiteStore::where(['id' => $store_id, 'cp_id' => $accountinfo['cp_id']])->first();
                if (!$storeinfo) {
                    return response()->json(['code' => '001', 'msg' => '无效门店参数']);
                }
            }
        }

        $cp_id = $accountinfo['cp_id'];
        if ($filepathname != '' && file_exists(storage_path() . $filepathname) && is_file(storage_path() . $filepathname)) {
            $file = storage_path() . $filepathname;
            $data = Excel::toArray(null, $file)[0];

            // 检查数据条数，排除表头
            $dataCount = count($data) - 1; // 减去表头行
            if ($dataCount > 10001) {
                return response()->json(['code' => '001', 'msg' => '导入数据条数不得超过10000条，当前共' . $dataCount . '条']);
            }

            // 预先获取会员等级和业务员信息
            $memberLevels = SiteMemberLv::where(['cp_id' => $cp_id, 'is_del' => 1])
                ->pluck('id', 'lv_name')
                ->toArray();

            $salesAccounts = Account::where(['cp_id' => $cp_id, 'is_del' => 1])
                ->pluck('id', 'real_name')
                ->toArray();

            $ins_data = [];
            $duplicateRows = []; // 记录重复行号

            // 先检查所有手机号是否有重复
            $mobiles = [];
            for ($i = 1; $i < count($data); $i++) {
                if (!empty($data[$i][0])) {
                    $mobiles[] = $data[$i][0];
                }
            }

            if (!empty($mobiles)) {
                $existingMembers = Member::where(['cp_id' => $cp_id, 'is_del' => 1])
                    ->whereIn('mobile', $mobiles)
                    ->pluck('mobile')
                    ->toArray();

                if (!empty($existingMembers)) {
                    // 找出重复行号
                    foreach ($data as $key => $val) {
                        if ($key == 0) continue;
                        if (!empty($val[0]) && in_array($val[0], $existingMembers)) {
                            $duplicateRows[] = $key + 1;
                        }
                    }

                    if (!empty($duplicateRows)) {
                        return response()->json(['code' => '001', 'msg' => implode(',', $duplicateRows) . '行信息已存在']);
                    }
                }
            }

            $Validate = new ValidateMemberMember();
            foreach ($data as $key => $val) {
                if ($key == 0) { //表头跳过
                    if (count($val) != 10) {
                        return response()->json(['code' => '001', 'msg' => '导入数据格式错误']);
                    }
                    continue;
                }
                if ($val[0] == '') {
                    continue;
                }

                if (empty($val[5])) {
                    $formattedDate = '';
                } else {
                    $dateTimeObject = Date::excelToDateTimeObject($val[5]);
                    $formattedDate = $dateTimeObject->format('Y-m-d');
                }

                $valdata = [
                    'cp_id' => $cp_id,
                    'store_id' => $store_id,
                    'mobile' => strval($val[0]),
                    'mem_card_no' => strval($val[1]),
                    'real_name' => strval($val[2]),
                    'gender' => $val[3] == '男' ? 1 : ($val[3] == '女' ? 2 : 0),
                    'member_lv' => isset($memberLevels[$val[4]]) ? $memberLevels[$val[4]] : 0,
                    'solar_bdate' => strval($formattedDate),
                    'points_total' => intval($val[6]),
                    'points_current' => intval($val[6]),
                    'shopping_account_id' => isset($salesAccounts[$val[7]]) ? $salesAccounts[$val[7]] : 0,
                    'address' => strval($val[8]),
                    'remark' => strval($val[9]),
                    'create_at' => time(),
                    'update_at' => time(),
                    'is_old' => 2,
                ];

                if (!$Validate->check($valdata)) {
                    continue;
                }

                $ins_data[] = $valdata;
            }

            // 分批插入数据
            if (!empty($ins_data)) {
                DB::transaction(function () use ($ins_data) {
                    $batchSize = 500;
                    foreach (array_chunk($ins_data, $batchSize) as $batch) {
                        Member::insert($batch);
                    }
                }, 3);
            }

            return response()->json(['code' => '000', 'msg' => '数据导入成功，共导入' . count($ins_data) . '条数据']);
        } else {
            return response()->json(['code' => '001', 'msg' => '文件不存在'], 200);
        }
    }

}
